const dayjs = require('./dayjs/dayjs.min');
const globalData = getApp().globalData;
const {
  gotoLogin
} = require('../../utils/util');
import fetch from "../../utils/fetch";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    weekdayCount: 7,
    weekIndexMap: ['日', '一', '二', '三', '四', '五', '六'], // 数字中文映射
    todayDay: '01',
    weekCalendar: ['01', '02', '03', '04', '05', '06', '07'], // 一周的日期
    index: 0,
    weeks: [], // 里面存放三个数组，分别为上一周，当前周和下一周的日期
    currentDate: dayjs().format("YYYY-MM-DD"),
    today: dayjs().format("YYYY-MM-DD"),
    startDate: null, // 周历数组开始的时间
    endDate: null, // 周历数组结束的时间
    ingested: 0, // 饮食摄入
    targetHeat: 1300, // 推荐摄入
    exerciseHeat: 0, // 运动消耗
    canEat: 1300, // 还能摄入或者已经超出
    nutritionData: [{
        name: '碳水化合物',
        percent: 85.22,
        weight: 125
      },
      {
        name: '蛋白质',
        percent: 14.22,
        weight: 49
      },
      {
        name: '脂肪',
        percent: 0.23,
        weight: 41
      }
    ],
    foodIcons: [{
        name: '早餐',
        suggest: '',
        curHeat: 0,
        img: '../../assets/record_icons/breakfast.png'
      },
      {
        name: '午餐',
        suggest: '',
        curHeat: 0,
        img: '../../assets/record_icons/lunch.png'
      },
      {
        name: '晚餐',
        suggest: '',
        curHeat: 0,
        img: '../../assets/record_icons/dinner.png'
      },
      {
        name: '加餐',
        suggest: '',
        curHeat: 0,
        img: '../../assets/record_icons/jiacan.png'
      }
    ],
    foodRecord: {}, // 一天饮食记录
    navArr:[
      { 
        type:1,
        img: "../../assets/images/kepu.png",
        title: '知识科普'
      },
      {
        type:2,
        img: "../../assets/images/activity.png",
        title: '热门活动'
      }
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.initWeeks();
    // 如果登录，根据用户信息获取一天的目标热量和记录
    if (globalData.isLogin) {
      const userId = globalData.userInfo.id;
      this.initValues(userId);
    } else {
      this.initCanvas()
    }

  },
  refresh: false, //该变量用于页面onshow重新获取食物记录数据，并且onload如果执行则不重复执行onshow
  onShow() {
    if (this.refresh && globalData.isLogin) {
      const userInfo = wx.getStorageSync('userInfo');
      const userId = userInfo.id;
      this.initValues(userId);
      this.getExerciseData(userId);
    } else {
      this.refresh = true;
    }
  },
  // 日期切换
  change(e) {
    let {
      currentDate,
      index,
      weeks,
      startDate,
      endDate
    } = this.data
    let current = e.detail.current
    let aDate = current - index == -2 || current - index == 1 ? endDate : startDate

    if (current == 0) {
      weeks = [this.getWeek(0, aDate), this.getWeek(1, aDate), this.getWeek(-1, aDate)]
      startDate = weeks[2][0].date,
        endDate = weeks[1][6].date,
        currentDate = weeks[0][0].date
    }
    if (current == 1) {
      weeks = [this.getWeek(-1, aDate), this.getWeek(0, aDate), this.getWeek(1, aDate)]
      startDate = weeks[0][0].date,
        endDate = weeks[2][6].date,
        currentDate = weeks[1][0].date
    }
    if (current == 2) {
      weeks = [this.getWeek(1, aDate), this.getWeek(-1, aDate), this.getWeek(0, aDate)]
      startDate = weeks[1][0].date,
        endDate = weeks[0][6].date,
        currentDate = weeks[2][0].date
    }
    this.setData({
      weeks,
      startDate,
      endDate,
      currentDate,
      index: current
    })
    const userId = globalData.userInfo.id;
    this.getExerciseData(userId);
  },
  // 选中日期
  tapDate(e) {
    let date = e.currentTarget.dataset.date
    this.setData({
      currentDate: date
    })
    const userId = globalData.userInfo.id;
    this.getExerciseData(userId);
  },
  // 初始化周历weeks数组
  initWeeks() {
    // 构造一个数组[[],[],[]]，里边放3个星期的数据,[0]放本周，[1]放下一周,[2]放上一周 
    let {
      weeks,
      startDate,
      endDate,
      currentDate
    } = this.data
    weeks = [this.getWeek(0, currentDate), this.getWeek(1, currentDate), this.getWeek(-1, currentDate)]
    startDate = weeks[2][0].date,
      endDate = weeks[1][6].date

    this.setData({
      weeks,
      startDate,
      endDate
    })
  },
  // direction 接收 0,1,-1三个值，分别代表，本周，下周，上周
  getWeek(direction, date) {
    date = dayjs(date)
    let firstDayOfWeek = date.subtract(date.day(), "day");
    let arr = []
    for (let i = direction * 7; i < (1 + direction) * 7; i++) {
      let d = firstDayOfWeek.add(i, "day")
      arr.push({
        date: d.format("YYYY-MM-DD"),
        day: d.format("DD"),
      })
    }
    return arr;
  },
  initCanvas() {
    const query = wx.createSelectorQuery()
    query.select('#circle').fields({
      node: true,
      size: true
    }).exec((res) => {
      const canvas = res[0].node;
      const ctx = canvas.getContext('2d');
      //获取分辨率
      this.dpr = wx.getSystemInfoSync().pixelRatio;
      //根据分辨率设置宽高
      canvas.width = res[0].width * this.dpr;
      canvas.height = res[0].height * this.dpr;
      ctx.scale(this.dpr, this.dpr);
      this.canvas = canvas;
      this.ctx = ctx;
      if (ctx) {
        this.drawCircle();
      }
    })
  },
  drawCircle() {
    const {
      ctx,
      canvas,
      dpr
    } = this;
    // 清除画布的所有内容
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    // 画内圆
    ctx.lineWidth = 2 / dpr;
    ctx.strokeStyle = "#E76F51";
    ctx.beginPath();
    // 圆心
    ctx.translate(75, 75);
    // 创建圆
    ctx.arc(0, 0, 75 - 12 / dpr, 0, 2 * Math.PI);
    // 绘制
    ctx.stroke();

    // 画外圆
    const {
      canEat,
      targetHeat,
      ingested,
      exerciseHeat
    } = this.data;
    let per = 2;
    if (canEat > 0) {
      per = 2 * (ingested) / (targetHeat + exerciseHeat);
    }

    ctx.lineWidth = 24 / dpr;
    ctx.strokeStyle = "#E76F51";
    // 设置线条末端线帽的样式
    ctx.lineCap = "round";
    ctx.beginPath();
    // 将画布的坐标系旋转90度,起点从12点位置开始
    ctx.rotate(-90 * Math.PI / 180);
    ctx.arc(0, 0, 75 - 12 / dpr, 0, per * Math.PI);
    ctx.stroke();
  },
  initValues(userId) {
    let {targetHeat} = this.data;
    let metabolicRate; // 基础代谢率
    // 女性基础代谢率=661+9.6*体重+1.72*身高-4.7*年龄
    if (globalData.userInfo.sex == 2) {
      metabolicRate = 661 + 9.6 * globalData.userInfo.weight + 1.72 * globalData.userInfo.height - 4.7 * globalData.userInfo.age
    } else {
      // 男性基础代谢率=67+13.73*体重+5*身高-6.9*年龄
      metabolicRate = 67 + 13.73 * globalData.userInfo.weight + 5 * globalData.userInfo.height - 6.9 * globalData.userInfo.age
    }
    // 根据代谢率计算应该摄入的热量
    targetHeat = parseInt(metabolicRate * 1.2 * 0.85);
    const foodIcons = this.data.foodIcons;
    // 计算每餐推荐摄入
    foodIcons[0].suggest = parseInt(targetHeat * 0.25) + '-' + parseInt(targetHeat * 0.30)
    foodIcons[1].suggest = parseInt(targetHeat * 0.35) + '-' + parseInt(targetHeat * 0.40)
    foodIcons[2].suggest = parseInt(targetHeat * 0.25) + '-' + parseInt(targetHeat * 0.30)
    foodIcons[3].suggest = 0 + '-' + parseInt(targetHeat * 0.10)
    this.setData({
      targetHeat,
      foodIcons
    })
    this.getExerciseData(userId);
  },
  getExerciseData(userId){
    let {targetHeat, exerciseHeat, canEat,currentDate} = this.data;
    if(userId){
      fetch(`/sportsrecord/list?userId=${userId}&recordDate=${currentDate}`).then(res => {
        if (res.data.sumHeat !== 0) {
          exerciseHeat = res.data.sumHeat
        } else {
          exerciseHeat = 0;
        }
        canEat = targetHeat + exerciseHeat;
        this.setData({
          exerciseHeat,
          canEat
        })
        this.getFoodRecord(userId);
      })
    }
    
  },
  // 获取饮食数据
  getFoodRecord(userId) {
    let {
      targetHeat,
      exerciseHeat
    } = this.data;
    fetch('/foodRecord/', {
      userId,
      recordDate: this.data.currentDate
    }, 'post').then(res => {
      const {
        foodRecord,
        nutritionData
      } = res.data;
      const foodIcons = this.data.foodIcons;
      const foodRecordKey = Object.keys(foodRecord);
      let ingested = 0;
      if (foodRecordKey.length > 0) {
        foodRecordKey.forEach(item => {
          ingested += foodRecord[item].totalHeat;
        })
        ingested = parseFloat(ingested.toFixed(2));
      } else {
        foodIcons.forEach(item => {
          item.curHeat = 0;
        })
      }
      if (foodRecord.breakfast) {
        foodIcons[0].curHeat = parseFloat(foodRecord.breakfast.totalHeat.toFixed(2));
      }
      if (foodRecord.lunch) {
        foodIcons[1].curHeat = parseFloat(foodRecord.lunch.totalHeat.toFixed(2));
      }
      if (foodRecord.dinner) {
        foodIcons[2].curHeat = parseFloat(foodRecord.dinner.totalHeat.toFixed(2));
      }
      if (foodRecord.add) {
        foodIcons[3].curHeat = parseFloat(foodRecord.add.totalHeat.toFixed(2));
      }
      let canEat = (targetHeat + exerciseHeat - ingested).toFixed(2);
      this.setData({
        foodIcons,
        foodRecord: foodRecord,
        nutritionData,
        ingested,
        canEat
      })
      this.initCanvas();
    })
  },
  // 跳转去食物页面
  gotoRecord(e) {
    if (!globalData.isLogin) {
      gotoLogin();
      return;
    }
    const recordTime = e.currentTarget.dataset.recordTime;
    const recordDate = this.data.currentDate;
    const canvasdata = {
      ingested: this.data.ingested,
      canEat: this.data.canEat,
      targetHeat: this.data.targetHeat,
      exerciseHeat: this.data.exerciseHeat,
      nutritionData: this.data.nutritionData
    }
    wx.setStorageSync('canvasdata', canvasdata)
    wx.navigateTo({
      url: `../foodRecord/foodRecord?recordTime=${recordTime}&recordDate=${recordDate}`,
    })
  },
  gotoSport() {
    const recordDate = this.data.currentDate;
    wx.navigateTo({
      url: `../sports/sports?recordDate=${recordDate}`,
    })
    // wx.navigateTo({
    //   url: `../foodRecord/foodRecord?recordDate=${recordDate}`,
    // })
  },
  gotoKnowledge(){
    wx.navigateTo({
      url: '../knowledge/knowledge',
    })
  },
  gotoActivity(){
    wx.navigateTo({
      url: '../activity/activity',
    })
  },
  gotoNav(e){
    const type = e.currentTarget.dataset.navId;
    if(type == 1){
      this.gotoKnowledge();
    }else{
      this.gotoActivity();
    }
  }
})